package com.itheima.server.controller;

import com.itheima.common.core.domain.AjaxResult;
import com.itheima.common.exception.job.TaskException;
import com.itheima.quartz.domain.SysJob;
import com.itheima.quartz.mapper.SysJobMapper;
import com.itheima.quartz.service.ISysJobService;
import com.itheima.quartz.util.ScheduleUtils;
import com.itheima.server.domain.CluBusSave;
import com.itheima.server.service.RuleService;
import com.itheima.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/rule")
@RequiredArgsConstructor
public class RuleController {
    private static final Logger log = LoggerFactory.getLogger(RuleController.class);
    private final ISysDictDataService sysDictDataService;
    private final RuleService ruleService;
    private final SysJobMapper jobMapper;
    private final Scheduler scheduler;


    /**
     * 新增配置
     * @param cluBusSave
     * @return
     */
    @PostMapping("/pool")
    public AjaxResult saveDisposition(@RequestBody CluBusSave cluBusSave) {

        ruleService.save(cluBusSave);

        return AjaxResult.success();
    }

    /**
     * 线索配置回显
     * @param type
     * @return
     */
    @GetMapping("/pool/{type}")
    public AjaxResult getClueList(@PathVariable Integer type){
      CluBusSave cluBusSave =  ruleService.getDisposition(type);
      return AjaxResult.success(cluBusSave);

    }

    /**
     * 修改配置
     * @param cluBusSave
     * @return
     */
    @PutMapping("/pool")
    public AjaxResult updateDisposition(@RequestBody CluBusSave cluBusSave) {

        ruleService.saveOrUpdate(cluBusSave);
        //获取corn表达式

        //判断商机
        if (cluBusSave.getType().equals("1")){

            //设置定时任务参数
            SysJob job = new SysJob();
            job.setJobName("商机定时任务");
            job.setInvokeTarget("businessJob.executeBusiness");
            //一小时执行一次
            job.setCronExpression("0 0 */1 * * ?");
//            job.setCronExpression("0/5 * * * * ?");
            job.setMisfirePolicy("1");
            job.setConcurrent("1");
            job.setStatus("0");
            job.setJobGroup("DEFAULT");

            try {
                //删除旧任务
                List<SysJob> sysJobList = jobMapper.selectJobList(job);
                for (SysJob sysJob : sysJobList) {
                    jobMapper.deleteJobById(sysJob.getJobId());
                    scheduler.deleteJob(ScheduleUtils.getJobKey(sysJob.getJobId(), sysJob.getJobGroup()));
                }
                //添加新任务
                jobMapper.insertJob( job);
                ScheduleUtils.createScheduleJob(scheduler, job);
            } catch (Exception e) {
                log.error("定时任务添加失败", e);
            }
        }else if (cluBusSave.getType().equals("0")){
            //设置定时任务参数
            SysJob job = new SysJob();
            job.setJobName("线索定时任务");
            job.setInvokeTarget("clueJob.executeClue");
            //一小时执行一次
            job.setCronExpression("0 0 */1 * * ?");
//            job.setCronExpression("0/5 * * * * ?");
            job.setMisfirePolicy("1");
            job.setConcurrent("1");
            job.setStatus("0");
            job.setJobGroup("DEFAULT");

            try {
                //删除旧任务
                List<SysJob> sysJobList = jobMapper.selectJobList(job);
                for (SysJob sysJob : sysJobList) {
                    jobMapper.deleteJobById(sysJob.getJobId());
                    scheduler.deleteJob(ScheduleUtils.getJobKey(sysJob.getJobId(), sysJob.getJobGroup()));
                }
                //添加新任务
                jobMapper.insertJob( job);
                ScheduleUtils.createScheduleJob(scheduler, job);
            } catch (Exception e) {
                log.error("定时任务添加失败", e);
            }

        }


        return AjaxResult.success();
    }

    /**
     * 商机配置回显
     * @param type
     * @return
     */
    @GetMapping("/list/{type}")
    public AjaxResult getBussinessList(@PathVariable Integer type) {
        CluBusSave cluBusSave = ruleService.getDisposition(type);
        return AjaxResult.success(cluBusSave);
    }


}
